<template>
  <div class="app-container">

    <div class="tabInfo">
    <div class="search">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
        class="demo-form-inline"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="监听类型" prop="type">
          <el-select
            v-model="queryParams.type"
            placeholder="请选择监听类型"
            clearable
          >
            <el-option
              v-for="dict in sys_listener_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="handleQuery"
            ><el-icon><Search /></el-icon>搜索</el-button
          >
          <el-button size="mini" @click="resetQuery"
            ><el-icon><Refresh /></el-icon>重置</el-button
          >
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:listener:add']"
            ><el-icon><CirclePlus /></el-icon>新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:listener:edit']"
            ><el-icon><Edit /></el-icon>修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:listener:remove']"
            ><el-icon><Delete /></el-icon>删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:listener:export']"
            ><el-icon><Download /></el-icon>导出</el-button
          >
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
    </div>

    <div class="table" :style="{ height: tabHeight + 'px' }">
      <el-table
        :height="tabHeight"
        v-loading="loading"
        :data="listenerList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="监听类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="sys_listener_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="事件类型" align="center" prop="eventType" />
        <el-table-column label="值类型" align="center" prop="valueType">
          <template #default="scope">
            <dict-tag
              :options="sys_listener_value_type"
              :value="scope.row.valueType"
            />
          </template>
        </el-table-column>
        <el-table-column label="执行内容" align="center" prop="value" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:listener:edit']"
              ><el-icon><Edit /></el-icon>修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:listener:remove']"
              ><el-icon><Delete /></el-icon>删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <pagination
        v-show="total > 10"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    </div>

    <!-- 添加或修改流程监听对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="监听类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择监听类型">
            <el-option
              v-for="dict in sys_listener_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="事件类型"
          prop="eventType"
          v-if="form.type === '1'"
        >
          <el-select v-model="form.eventType" placeholder="请选择事件类型">
            <el-option
              v-for="dict in taskListenerEventList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事件类型" prop="eventType" v-else>
          <el-select v-model="form.eventType" placeholder="请选择事件类型">
            <el-option
              v-for="dict in executionListenerEventList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="值类型" prop="valueType">
          <el-radio-group v-model="form.valueType">
            <el-radio
              v-for="dict in sys_listener_value_type"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="执行内容" prop="value">
          <el-input v-model="form.value" placeholder="请输入执行内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import { getCommonTableHeight } from "@/utils/commonTableHeight.js";

import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  listListener,
  getListener,
  delListener,
  addListener,
  updateListener,
} from "@/api/flowable/listener";

const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const listenerList = ref([]);
const title = ref("");
const open = ref(false);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  type: null,
  eventType: null,
  valueType: null,
  value: null,
  status: null,
});
const form = ref({});
const rules = ref({});
const taskListenerEventList = ref([
  { label: "create", value: "create" },
  { label: "assignment", value: "assignment" },
  { label: "complete", value: "complete" },
  { label: "delete", value: "delete" },
]);
const executionListenerEventList = ref([
  { label: "start", value: "start" },
  { label: "end", value: "end" },
  { label: "take", value: "take" },
]);

const { proxy } = getCurrentInstance();
const { sys_listener_value_type } = proxy.useDict("sys_listener_value_type");
const { sys_listener_type } = proxy.useDict("sys_listener_type");
const tabHeight = ref(0);

const updateViewportHeight = () => {
  tabHeight.value = getCommonTableHeight();
};
onMounted(() => {
  updateViewportHeight(); // 初始化视口高度
  window.addEventListener("resize", updateViewportHeight); // 监听窗口大小变化
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", updateViewportHeight); // 移除监听
});
const getList = () => {
  loading.value = true;

  listListener(queryParams).then((response) => {
    listenerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

const cancel = () => {
  open.value = false;
  reset();
};
const formRef = ref(null);
const reset = () => {
  form.value = {
    id: null,
    name: null,
    type: null,
    eventType: null,
    valueType: null,
    value: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    status: null,
    remark: null,
  };
  // this.resetForm("form"); // Vue 3 中不需要手动调用 resetForm，除非你有特定的表单重置逻辑
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  // this.resetForm("queryForm"); // Vue 3 中不需要手动调用 resetForm，除非你有特定的表单重置逻辑
  handleQuery();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加流程监听";
};

const handleUpdate = (row) => {
  reset();
  const id = row.id || ids.value;
  getListener(id).then((response) => {
   
    form.value = response.data;
    open.value = true;
    title.value = "修改流程监听";
  });
};

const submitForm = () => {
  const formEl = formRef.value;
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateListener(form.value).then((response) => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addListener(form.value).then((response) => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

// const submitForm = () => {
//   this.$refs["form"].validate(valid => { // Vue 3 中不再使用 $refs 进行表单验证，除非你使用了特定的表单库
//     if (valid) {
//       if (this.form.id != null) {
//         updateListener(this.form).then(response => {
//           this.$modal.msgSuccess("修改成功");
//           this.open = false;
//           this.getList();
//         });
//       } else {
//         addListener(this.form).then(response => {
//           this.$modal.msgSuccess("新增成功");
//           this.open = false;
//           this.getList();
//         });
//       }
//     }
//   });
// };

const handleDelete = (row) => {
  const ids = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除流程监听编号为"' + ids + '"的数据项？')
    .then(() => {
      delListener(ids).then(() => {
        getList();
        ElMessage.success("删除成功");
      });
    })
    .catch(() => {});
};

const handleExport = async () => {
  // this.download('system/listener/export', { ...this.queryParams }, `listener_${new Date().getTime()}.xlsx`); // Vue 3 中可以使用 axios 或其他库进行下载

  try {
    // 构造请求参数
    const params = { ...queryParams };

    // 调用下载方法
    await proxy.download(
      "system/listener/export",
      params,
      `listener_${new Date().getTime()}.xlsx`
    );

    ElMessage.success("导出成功");
  } catch (error) {
    ElMessage.error("导出失败，请稍后重试");
  }
};

onMounted(() => {
  getList();
});
</script>
<style>

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

</style>
